package up.android.camera;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import up.android.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;

import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class CameraActivity extends Activity implements Callback,PictureCallback {
	
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	private Bitmap snapshot;
	private ImageButton backButton;
	private ImageButton takeButton;
	private Camera mCamera; 


	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cameraactivity);
        
		mSurfaceView = (SurfaceView) findViewById(R.id.SurfaceView01);


		mSurfaceHolder = mSurfaceView.getHolder();

		mSurfaceHolder.addCallback(this);

		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		
		backButton = (ImageButton)findViewById(R.id.btnRefreshPicture);
		backButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				showImage(false);
			}
		});
		
		takeButton = (ImageButton)findViewById(R.id.btnTakePicture);
		takeButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(mCamera != null)
				{
					mCamera.takePicture(null,null, CameraActivity.this);
				}
				showImage(true);
			}
		});		
    }
    
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if(mCamera == null)
		{
			mCamera = Camera.open();
			Camera.Parameters p = mCamera.getParameters();
			List<Camera.Size> sizes = p.getSupportedPreviewSizes();
			p.setPreviewSize(width, height);
			mCamera.setParameters(p);
			mCamera.setDisplayOrientation(90);
			try
			{
				mCamera.setPreviewDisplay(holder);
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			mCamera.startPreview();
		}
		
	}
	
	public void surfaceCreated(SurfaceHolder holder) {
		
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		if(mCamera != null)
		{
			mCamera.stopPreview();
			mCamera.release();
			mCamera=null;
		}

	}

	private void showImage(boolean preview)
	{
		ImageView view = (ImageView)findViewById(R.id.ImageView01);
		view.setVisibility(preview?View.VISIBLE : View.GONE);
		mSurfaceView.setVisibility(preview? View.GONE : View.VISIBLE);
		backButton.setVisibility(preview?View.VISIBLE : View.GONE);
		takeButton.setVisibility(preview?View.GONE : View.VISIBLE);
	}

	public void onPictureTaken(byte[] data, Camera camera) {
		ImageView view = (ImageView)findViewById(R.id.ImageView01);
		
		BitmapFactory.Options option = new BitmapFactory.Options();
		option.inSampleSize=4;
		Bitmap bm = BitmapFactory.decodeByteArray(data,
	    		 0,data.length,option); 
		
		if(snapshot != null)
			snapshot.recycle();
		
		Matrix mat = new Matrix();
        mat.postRotate(90);
        Bitmap bMapRotate = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mat, true);
        bm.recycle();

        snapshot = bMapRotate;
        view.setImageBitmap(snapshot);
		
		mCamera.release();
		mCamera = null;
	    showImage(true);
	    
	    String url = "http://10.1.254.189:8080/AndroidServer/Calculadora";
		
		HttpClient http = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		
		post.setHeader("Content-Type","application/json");
		
		Base64 base = new Base64();
		
		try {
			JSONObject obj = new JSONObject();
			base.encodeBytes(data);
			obj.put("par1", data);
			obj.put("action", "save");

			post.setEntity(new StringEntity(obj.toString()));
			HttpResponse response = http.execute(post);
			InputStream in = response.getEntity().getContent();

			InputStreamReader reader = new InputStreamReader(in);
			BufferedReader b = new BufferedReader(reader);
			String s = "";
			String line;
			while((line = b.readLine())!= null)
				s+=line+"\n";

			JSONObject result = new JSONObject(s);
			Toast t = Toast.makeText(getApplicationContext(), "Foto Salva !", Toast.LENGTH_LONG);
			t.show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e("Componentes",e.getMessage(),e);
		} 
	}
}